﻿using Engine;
using Game.NetWork;
using Game.Server.Event;
using Game.Server.PlayerEvent;
using GameEntitySystem;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using static System.Net.Mime.MediaTypeNames;

namespace Game.Server.Plugins
{
    public class TravelPathZHPlugin : ServerPlugin, ICreatureSpawnEventHandle
    {
        public override int Version => 10000;

        public override string Name => "玩家行径记录";

        public byte FirstLevel => 0;

        public SubsystemGameInfo SubsystemGameInfo;

        public SubsystemTime SubsystemTime;

        public SubsystemPlayers SubsystemPlayers;

        public List<string> TravelPaths = new List<string> ();

        public static string TravelPath;

        public override void Initialize()
        {
            CreatureSpawnEventManager.AddObject(this);
        }

        public string GetPluginDataByWorldPath(string fileName)
        {
            string pluginDataPath = Storage.GetSystemPath("app:/PluginData");
            if (!Directory.Exists(pluginDataPath))
            {
                Directory.CreateDirectory(pluginDataPath);
            }
            string worldName = GameManager.Project.FindSubsystem<SubsystemGameInfo>().WorldSettings.Name;
            string dataByWorldPath = Storage.CombinePaths(pluginDataPath, worldName);
            if (!Directory.Exists(dataByWorldPath))
            {
                Directory.CreateDirectory(dataByWorldPath);
            }
            return Storage.CombinePaths(dataByWorldPath, fileName);
        }

        public override void Load()
        {
            TravelPath = GetPluginDataByWorldPath("TravelPath");
            SubsystemGameInfo = GameManager.Project.FindSubsystem<SubsystemGameInfo>();
            SubsystemTime = GameManager.Project.FindSubsystem<SubsystemTime>();
            SubsystemPlayers = GameManager.Project.FindSubsystem<SubsystemPlayers>();
        }

        public override void Save()
        {
            if (TravelPaths.Count == 0) return;
            if (!Directory.Exists(TravelPath))
            {
                Directory.CreateDirectory(TravelPath);
            }
            string path = Storage.CombinePaths(TravelPath, $"Time-{DateTime.Now.Year}-{DateTime.Now.Month}-{DateTime.Now.Day}.csv");
            using (FileStream fileStream = File.Open(path, FileMode.OpenOrCreate))
            {
                fileStream.Position = fileStream.Length;
                using (StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8))
                {
                    foreach(string msg in TravelPaths)
                    {
                        streamWriter.WriteLine(msg);
                    }
                    streamWriter.Flush();
                    TravelPaths.Clear();
                }
            }
        }

        public bool Update(SubsystemCreatureSpawn subsystemCreatureSpawn, float dt)
        {
            if (SubsystemTime != null && SubsystemTime.PeriodicGameTimeEvent(5f, 1f))
            {
                foreach (var player in SubsystemPlayers.ComponentPlayers)
                {
                    Point3 point = new Point3(player.ComponentBody.Position);
                    Point2 point2 = Terrain.ToChunk(player.ComponentBody.Position.XZ);
                    string mes = $"{player.PlayerData.Client.CommunityAccountId},{player.PlayerData.Name},{point2.X},{point2.Y},{DateTime.Now.ToString("hh:mm:ss")},{point.X},{point.Y},{point.Z}";
                    TravelPaths.Add(mes);
                }
            }
            return true;
        }

        public void OnEntityAdded(SubsystemCreatureSpawn subsystemCreatureSpawn, Entity entity)
        {
        }

        public void OnEntityRemoved(SubsystemCreatureSpawn subsystemCreatureSpawn, Entity entity)
        {
        }

        public void OnPlayerSpawned(PlayerData playerData, Entity playerEntity, Vector3 position)
        {
        }

        public void InitCreatureTypes(SubsystemCreatureSpawn subsystemCreatureSpawn, List<SubsystemCreatureSpawn.CreatureType> creatureTypes)
        {
        }
    }
}